//
//  Device.swift
//  Alamofire
//
//  Created by 李然 on 2024/4/27.
//

import Foundation
import CRPEarPhone

public class Device: Codable {
    
    /// 耳机仓版本号
    public var version: String = ""
    /// 耳机仓 mac 地址
    public var macAddress: String = ""
    /// 耳机仓名字
    public var localName: String = ""
    /// 耳机仓产品类型
    public var productType: Int = 0
    /// 耳机仓产品外观
    public var productStyle: Int = 0
    /// 耳机类型
    public var earSytle: Int = 0
    
    public var discovery: CRPDiscovery?
    
    public init(discovery: CRPDiscovery) {
        self.discovery = discovery
        self.macAddress = discovery.mac ?? ""
        self.localName = discovery.localName ?? ""
        self.version = discovery.info?.version ?? ""
        self.productType = discovery.info?.productType ?? 0
        self.productStyle = discovery.info?.productStyle ?? 0
        self.earSytle = discovery.info?.earSytle ?? 0
    }
    
    public var isCharging: Bool {
        return (self.discovery?.info?.charging ?? 0) == 1
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(version, forKey: .version)
        try container.encode(macAddress, forKey: .macAddress)
        try container.encode(localName, forKey: .localName)
        try container.encode(productType, forKey: .productType)
        try container.encode(productStyle, forKey: .productStyle)
        try container.encode(earSytle, forKey: .earSytle)
    }
    
    required public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        version = try container.decode(String.self, forKey: .version)
        macAddress = try container.decode(String.self, forKey: .macAddress)
        localName = try container.decode(String.self, forKey: .localName)
        productType = try container.decode(Int.self, forKey: .productType)
        productStyle = try container.decode(Int.self, forKey: .productStyle)
        earSytle = try container.decode(Int.self, forKey: .earSytle)
    }
    
    private enum CodingKeys: String, CodingKey {
        case version
        case macAddress
        case localName
        case productType
        case productStyle
        case earSytle
    }
    
    private static let saveKey = "DeviceLocalKey"
    
    public static func current() -> Device? {
        if let data = UserDefaults.standard.data(forKey: saveKey),
           let model = try? JSONDecoder().decode(Device.self, from: data){
            return model
        }
        return nil
    }
    
    public func remove() {
        UserDefaults.standard.setValue(nil, forKey: Device.saveKey)
    }
    
    public func save() {
        if let data = try? JSONEncoder().encode(self) {
            UserDefaults.standard.setValue(data, forKey: Device.saveKey)
        }
    }
}
